<template>
    <div class="app-container">
      <div class="filter-container">
        <el-input
          v-model="listQuery.searchKey"
          placeholder="名称"
          style="width: 200px"
          class="filter-item"
        />
        <el-select
        v-model="listQuery.searchKey2"
        style="width: 180px"
        class="filter-item"
        :remote-method="getTypeList"
        filterable
        remote
        placeholder="请选择审批类型"
      >
        <el-option
          v-for="item in typeListOptions"
          :key="item.value"
          :label="item.label"
          :value="item.label"
        />
      </el-select>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="searchAndSort"
        >
          查找
        </el-button>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="项目编号" min-width="40px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{
              row.projectId
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{
              row.projectName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目负责人" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{
              row.projectOwnerName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="课题组" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{
              row.projectGroupName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属部门" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{
              row.projectDepartment
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责人电话" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{
              row.projectOwnerPhone
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目状态" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{
              row.projectStatus
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批类型" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{ row.projectStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          min-width="80"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{ row, $index }">
            <el-button
              v-if="row.projectActionType === '立项预审'"
              type="primary"
              size="mini"
              @click="$router.push(`/project/approve/preapprove/${row.id}`)"
            >
              立项预审
            </el-button>
            <el-button
              v-if="row.projectActionType === '立项伦理审批'"
              type="primary"
              size="mini"
              @click="$router.push(`/project/approve/ethicapprove/${row.id}`)"
            >
              立项伦理审批
            </el-button>
            <el-button
              v-if="row.projectActionType === '立项总审批'"
              type="primary"
              size="mini"
              @click="$router.push(`/project/approve/finalapprove/${row.id}`)"
            >
              总审批
            </el-button>
            <el-button
              v-if="row.projectActionType === '立项经费审批'"
              type="primary"
              size="mini"
              @click="$router.push(`/project/approve/costapprove/${row.id}`)"
            >
              院所领导审批费用
            </el-button>
            <el-button
              v-if="row.projectActionType === '变更审批'"
              type="primary"
              size="mini"
              @click="$router.push(`/project/approve/changeapprove/${row.id}/change/${row.changeId}`)"
            >
              变更审批
            </el-button>
            <el-button
              v-if="row.projectActionType === '中检审批'"
              type="primary"
              size="mini"
              @click="$router.push(`/project/approve/midapprove/${row.id}`)"
            >
              中检审批
            </el-button>
            <el-button
              v-if="row.projectActionType === '结项审批'"
              type="primary"
              size="mini"
              @click="$router.push(`/project/approve/endapprove/${row.id}`)"
            >
              结项审批
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.pageIndex"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
  </template>
  <script>
  import { searchTwo } from "@/utils";
  import Pagination from "@/components/Pagination";
  import { fetchProjectsByStatus } from '@/api/project';
  import { checkPermission } from '@/utils/permission';
  import { fetchResearchGroupById } from "@/api/research-group";
  import { fetchInProgressProjectChangeList } from "@/api/project-change";
  import projectCheckTypes from "@/data/projectCheckTypes";
  import { mapGetters } from "vuex";

  export default {
    name: "projectList",
    components: { Pagination },
    filters: {
      typeFilter(type) {
        return calendarTypeKeyValue[type];
      },
    },
    data() {
      return {
        tableKey: 0,
        totalList: [],
        list: null,
        total: 0,
        listLoading: false,
        typeListOptions: projectCheckTypes,
        listQuery: {
          pageIndex: 1,
          limit: 10,
          searchField1: 'projectName',
          searchKey1: '',
          searchField2: 'projectStatus',
          searchKey2: '',
        }
      };
    },
    created() {
      this.getList();
    },
    computed: {
    ...mapGetters(["id", "permissions"]),
    },
    methods: {
      checkPermission,
      getList() {
        // this.listLoading = true;
        const fetchStatusList = ["项目未立项", "项目进行中"]
        fetchProjectsByStatus(fetchStatusList).then((res) => {
          const permissionName = this.permissions.map(e => e.permissionName)

          if (res.data && res.data.length > 0) {
            // 立项预审，立项伦理审批，立项总审批，立项经费审批，变更审批，中检审批，结项审批
            res.data.forEach(async (item) => {
              // 项目未立项
            if (item.projectStatus === "项目未立项") {
              // 立项预审
              if (['科研处立项预审驳回', '科研处立项预审中'].includes(item.projectInformationCheckStatus) && checkPermission(['项目信息审批：预审'])) {
                console.log('科研处立项预审中')
                this.totalList.push(this.pushProjectItem(item, "立项审批", "立项预审"));
                console.log(' this.totalList', this.totalList)
                // 立项伦理审批
              } else if(['专家立项伦理审查驳回', '专家立项伦理审查中'].includes(item.projectInformationCheckStatus) && checkPermission(['项目信息审批：伦理'])) {
                if (this.id !== item.projectOwnerId) {
                  let isIn = false;
                  fetchResearchGroupById(item.projectGroupId)
                   .then((res) => {
                      const members = res.data[0].researchGroupMembers?.length > 0
                      ? JSON.parse(res.data[0].researchGroupMembers)
                      : [];
                      members.forEach(element => {
                        if (this.id === element.researchGroupMemberId) {
                          isIn =true;
                        }
                      });
                   })
                  .catch((err) => {
                    console.log(err);
                  });
                  const checkHistory = item.projectInformationCheckHistory?.length > 0
                    ? JSON.parse(item.projectInformationCheckHistory)
                      : [];
                  checkHistory.forEach(history => {
                        if (this.id === history.operatorId && history.name === '立项伦理审批' &&
                          history.status === '同意') {
                          isIn =true;
                        }
                      });
                  if (!isIn) {
                    this.totalList.push(this.pushProjectItem(item, "立项审批", "立项伦理审批"));
                  }
                }
              }  else if(['领导立项总审查驳回', '领导立项总审查中'].includes(item.projectInformationCheckStatus) && checkPermission(['项目信息审批：总审批'])) {
                this.totalList.push(this.pushProjectItem(item, "立项审批", "立项总审批"));
              } else if(['财务立项审查驳回', '财务立项审查中'].includes(item.projectInformationCheckStatus) && checkPermission(['项目信息审批：经费审批'])){
                this.totalList.push(this.pushProjectItem(item, "立项审批", "立项经费审批"));
              }
            } else if (item.projectStatus === "项目进行中" && item.projectChangeStatus !== "项目变更审批中") {
              if(['项目中期报告审批驳回', '项目中期报告审批中'].includes(item.projectCheckStatus) && checkPermission(['项目审批：中检'])){
                this.totalList.push(this.pushProjectItem(item, "中检审批", "中检审批"));
              } else if(['项目结项报告审批驳回', '项目结项报告审批中'].includes(item.projectCheckStatus) && checkPermission(['项目审批：结项'])){
                this.totalList.push(this.pushProjectItem(item, "结项审批", "结项审批"));
              }else if(['项目开题报告审批驳回', '项目开题报告审批中'].includes(item.projectCheckStatus) && checkPermission(['项目审批：开题'])){
                this.totalList.push(this.pushProjectItem(item, "开题审批", "开题审批"));
              }
            }
          });
          }
          // fetchInProgressProjectChangeList().then((changeRes) => {
          //   if (changeRes.data && changeRes.data.length > 0) {
          //     changeRes.data.forEach((item) => {
          //       this.totalList.push(this.pushChangeItem(item, "变更审批", "变更审批"));
          //     });
          //   }
          //   this.handleFilter();
          //   this.listLoading = false;
          // })
            this.handleFilter();
            this.listLoading = false;
        });
      },
      pushProjectItem(projectItem, status, action) {
        return {
          id: projectItem.id,
          projectId: projectItem.projectId,
          projectName: projectItem.projectName,
          projectOwnerName: projectItem.projectOwnerName,
          projectGroupName: projectItem.projectGroupName,
          projectDepartment: projectItem.projectDepartment,
          projectOwnerPhone: projectItem.projectOwnerPhone,
          projectStatus: status,
          projectActionType: action,
        }
      },
      pushChangeItem(projectItem, status, action) {
        return {
          id: projectItem.pId,
          projectId: projectItem.projectId,
          changeId: projectItem.id,
          projectName: projectItem.projectName,
          projectOwnerName: projectItem.projectOwnerName,
          projectGroupName: projectItem.projectGroupName,
          projectDepartment: projectItem.projectDepartment,
          projectOwnerPhone: projectItem.projectOwnerPhone,
          projectStatus: status,
          projectActionType: action,
        }
      },
      getTypeList(query) {
      if (query !== "") {
        this.typeListOptions = projectCheckTypes.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.typeListOptions = projectCheckTypes;
      }
    },
      handleFilter() {
        const result=searchTwo(this.totalList, this.listQuery);
        this.list = result.data;
        this.total=result.total;
      },
      searchAndSort() {
        this.listQuery.pageIndex = 1;
        this.handleFilter();
      },
    },
  };
  </script>
